import {HttpException, HttpStatus, Injectable} from "@nestjs/common";
import {Express} from "express"
import * as path from "path"
import * as fs from "fs-extra"
import * as moment from "moment"
import IHelper from "@/services/helper.service";
import IConstants from "@/core/constants";
import IResponse from "@/services/response.service";
import {ConfigService} from "@nestjs/config";
import {ReqProvider} from "@/core/providers/req.provider";

@Injectable()
export class SharedService {
  constructor(
    private readonly configService: ConfigService,
    private readonly reqProvider: ReqProvider
  ) {
    fs.ensureDirSync(path.join(IConstants.publicDir, "uploads"))
  }
  upload(file: Express.Multer.File) {
    const ALLOW_EXT_LIST: string[] = [".JPG", ".PNG", ".JPEG"]
    const MAX_SIZE: number = 5 * 1000 * 1000
    const extname = path.extname(file.originalname)
    if (file.size > MAX_SIZE) {
      throw new HttpException("File size cannot exceed 5M", HttpStatus.BAD_REQUEST)
    }
    if (!ALLOW_EXT_LIST.includes(extname.toUpperCase())) {
      throw new HttpException("The extname not supported to upload.", HttpStatus.BAD_REQUEST)
    }
    const relativePath = path.join("uploads", moment().format("YYYY/MM/DD"), `${IHelper.hash(32)}${extname}`)
    const absoluteFilepath = path.join(IConstants.publicDir, relativePath)
    fs.ensureFileSync(absoluteFilepath)
    fs.writeFileSync(absoluteFilepath, file.buffer)
    const url = path.join(this.configService.get("STATIC_PREFIX", "static"), relativePath)
    const finalUrl = [this.reqProvider.domain, ...url.split(path.sep)].join("/")
    return IResponse.success({ url: finalUrl })
  }
}